package com.bjpowernode.web.controller;

import com.bjpowernode.api.model.SysUser;
import com.bjpowernode.api.result.DubboResult;
import com.bjpowernode.api.vo.UserAccountInfo;
import com.bjpowernode.enums.Code;
import com.bjpowernode.utils.JwtUtil;
import com.bjpowernode.web.service.RealNameService;
import com.bjpowernode.web.service.SmsService;
import com.bjpowernode.web.views.ResultView;
import com.bjpowernode.web.views.UserView;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.crypto.SecretKey;
import javax.xml.transform.Result;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @description:
 * @author: panDeng_Zhu
 * @time: 2022/11/7 14:56
 */
@CrossOrigin
@Api(tags = "用户接口")
@RestController
public class UserController extends BaseController {

    @Value("${jwt-secretKey}")
    private String jwtSecretKey;

    @Resource
    private SmsService smsService;

    @Resource
    private RealNameService realNameService;

    //用户登录，获取token
    @ApiOperation(value = "用户登录", notes = "用户使用手机号登陆")
    @PostMapping("/v1/user/login")
    public ResultView userLogin(@RequestParam("phone") String phone,
                                @RequestParam("loginPassword") String loginPassword,
                                @RequestParam("smsCode") String smsCode) {
        ResultView<String> result = ResultView.FAIL();
        //1，检查请求的参数
        if (StringUtils.isAnyBlank(phone, loginPassword, smsCode)) {
            result.setEnumCode(Code.PARAMETER_NULL);
        } else {
            //登录
            SysUser user = userService.userLogin(phone, loginPassword);
            if (user != null) {
                //登录成功，生成token
                JwtUtil jwtUtil = new JwtUtil(jwtSecretKey);
                //token数据
                Map<String, Object> payLoad = new HashMap<>();
                payLoad.put("userId", user.getId());

                //生成token
                String jwt = jwtUtil.createJwt(payLoad, 120);//token有效期为2小时

                //返回给浏览器
                result = ResultView.SUCCESS();
                //用户的id，name，
                Map<String, Object> userMap = new HashMap<>();
                userMap.put("userId", user.getId());
                userMap.put("name", user.getName());
                userMap.put("phone", user.getPhone());

                result.setObject(userMap);
                result.setAccessToken(jwt);
            } else {
                result.setEnumCode(Code.PHONE_OR_PASSWORD_INVALID);
            }
        }
        return result;
    }

    //用户注册
    @ApiOperation(value = "用户注册", notes = "用户使用手机号注册")
    @PostMapping("/v1/user/register")
    public ResultView userRegister(@RequestParam("phone") String phone,
                                   @RequestParam("loginPassword") String loginPassword,
                                   @RequestParam("smsCode") String smsCode) {
        ResultView<String> result = ResultView.FAIL();
        if (StringUtils.isAnyBlank(phone, loginPassword, smsCode)) {
            result.setEnumCode(Code.PARAMETER_NULL);
        } else if (!smsService.checkSmsCode(phone, smsCode)) {//验证验证码是否有效
            result.setEnumCode(Code.SMS_CODE_INVALID);
        } else {
            //调用数据服务dataService，添加新的用户
            DubboResult dubboResult = userService.register(phone, smsCode);
            if (dubboResult.isInvoke()) {
                result = ResultView.SUCCESS();
            } else {
                result.setMsg(dubboResult.getMsg());
            }
        }

        return result;
    }

    //实名认证
    @ApiOperation(value = "实名认证")
    @PostMapping("/v1/user/realname")
    public ResultView userRealName(@RequestParam("phone") String phone,
                                   @RequestParam("userId") Integer userId,
                                   @RequestParam("name") String name,
                                   @RequestParam("idCard") String idCard,
                                   @RequestParam("smsCode") String smsCode) {
        ResultView<String> result = ResultView.FAIL();
        if (StringUtils.isAnyBlank(phone, name, idCard, smsCode)) {
            result.setEnumCode(Code.PARAMETER_NULL);
        } else {
            //调用实名认证的接口
            SysUser user = userService.queryByUserId(userId);
            if (user != null && user.getPhone().equals(phone)) {
                if (StringUtils.isBlank(user.getName())) {
                    boolean isOK = realNameService.handleRealName(userId, name, idCard);
                    if (isOK) {
                        result = ResultView.SUCCESS();
                    }
                } else {
                    //已经做过实名认证
                    result.setEnumCode(Code.NOT_RESTRY_REALNAME);
                }
            }
        }
        return result;
    }

    //查询用户信息
    @ApiOperation(value = "查询用户信息", notes = "获取用户信息(姓名，手机号，最后一次登录时间，余额)")
    @PostMapping("/v1/user/info")
    public ResultView queryUserInfo(@RequestHeader("userId") Integer userId) {
        ResultView<String> result = ResultView.FAIL();
        if (userId != null) {
            UserAccountInfo accountInfo = userService.queryUserAndAccountByUserId(userId);
            if (accountInfo != null) {
                result = ResultView.SUCCESS();
                //数据来自dataService服务
                UserView userView = new UserView();
                userView.setId(accountInfo.getId());
                userView.setLoginTime(DateFormatUtils.format(accountInfo.getLoginTime(), "yyy-MM-dd HH:mm:ss"));
                userView.setName(accountInfo.getName());
                userView.setPhone(accountInfo.getPhone());
                userView.setAccountMoney(accountInfo.getAccountMoney());
                result.setObject(userView);
            }
        }
        return result;
    }

    //用户退出登录
    @ApiOperation(value = "用户退出登录")
    @PostMapping("/v1/user/logout")
    public ResultView userLogout(@RequestHeader("userId") Integer userId,
                                 @RequestHeader("Authorization") String Authorization) {
        //记录token到redis，标志这个token无效
        String jwt = Authorization.substring(7);
        //设置过期时间
        stringRedisTemplate.opsForValue().set(jwt,"0",2, TimeUnit.HOURS);
        ResultView<String> resultView=ResultView.SUCCESS();
        return resultView;
    }
}
